package ecommerce.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import ecommerce.model.User;
import ecommerce.dao.UserDAO;
import ecommerce.dao.UserDAOImpl;

import java.util.Map;

public class LoginAction extends ActionSupport {
	
	private static final long serialVersionUID = 1L;
	private String username = null;
	private String password = null;
	
	public String loginPage() {
		return SUCCESS;
	}
	
	public String checkCredentials() {
		UserDAO userDAO = new UserDAOImpl();
		User user = userDAO.authenticate(username, password);
		if (user != null) {
			Map<String, Object> session = ActionContext.getContext().getSession();
			session.put("current_user", user.getUserId());
			session.put("logged_in", true);
			session.put("username", username);
			if (userDAO.getUserRole(user.getUserId()).equals("Administrator")) {
				session.put("role", 1);
				return "adminHome";
			} else {
				session.put("role", 2);
				return "memberHome";
			}
		} else {
			addFieldError("username", "Invalid credentials.");
			return INPUT;
		}
	}
	
	public String logout() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.clear();
		return SUCCESS;
	}
	
	public void validate() {
		if(username != null && password != null) {
			if(username.length() == 0) {	
				addFieldError("username", "Username is required.");
			}		
			if(password.length() == 0) {	
				addFieldError("password", "Password is required.");			
			}
		}
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getUsername() {
		return username;
	}
	
	public String getPassword() {
		return password;
	}
}
